local status, telescope = pcall(require, "telescope")
if not status then
	return print("Telescope not found!!!")
end

local pickers = require("telescope.pickers")
local finders = require("telescope.finders")
local builtin = require("telescope.builtin")
local action = require("telescope.actions")
local themes = require("telescope.themes")

local find_command
if not find_command then
	if 1 == vim.fn.executable("fd") then
		find_command = { "fd", "--type", "f" }
	elseif 1 == vim.fn.executable("rg") then
		find_command = { "rg", "--files" }
	end
end

telescope.setup({
	defaults = themes.get_ivy({
		vimgrep_arguments = {
			"rg",
			"--color=never",
			"--no-heading",
			"--with-filename",
			"--line-number",
			"--column",
			"--smart-case",
			"--trim",
		},
		prompt_prefix = "🔭 ",
		selection_caret = " ",
		path_display = { "smart" },
		layout_config = {
			height = 0.6,
		},
		mappings = {},
	}),
	pickers = {
		find_files = {
			find_command = find_command,
			theme = "dropdown",
			results_title = false,
			previewer = false,
			mappings = {
				n = {
					["cd"] = function(prompt_bufnr)
						local selection = require("telescope.actions.state").get_selected_entry()
						local dir = vim.fn.fnamemodify(selection.path, ":p:h")
						require("telescope.actions").close(prompt_bufnr)
						-- Depending on what you want put `cd`, `lcd`, `tcd`
						vim.cmd(string.format("silent lcd %s", dir))
					end,
				},
			},
		},
		oldfiles = {
			find_command = find_command,
			theme = "dropdown",
			results_title = false,
			previewer = false,
		},
    live_grep = {
      results_title = false,
    },
    buffers = {
			find_command = find_command,
			theme = "dropdown",
      results_title = false,
			previewer = false,
    }
	},
	extensions = {},
})

-- Mapp
local function keymaps()
	local map = require("utils.map")
	map("n", "<localleader>f", ":Telescope find_files <CR>")
	map("n", "<localleader>F", ":Telescope find_files hidden=true <CR>")
	map("n", "<localleader>s", ":Telescope current_buffer_fuzzy_find <CR>")
	map("n", "<localleader>S", ":Telescope live_grep <CR>")
	map("n", "<localleader>b", ":Telescope buffers <CR>")
	map("n", "<localleader>h", ":Telescope oldfiles <CR>")

	map("n", "<leader>fl", ":Telescope builtin <CR>")
	map("n", "<leader>th", ":Telescope help_tags <CR>")
	map("n", "<leader>fc", ":Telescope commands <CR>")
	map("n", "<leader>ch", ":Telescope command_history <CR>")
	map("n", "<leader>fr", ":Telescope registers<CR>")
end
keymaps()
